/**
 * <br>JAVACC DEMO 1.0<br>
 */
package com.apache.dict.service.helper;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.apache.cache.service.CacheManager;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.model.MethodParam;
import com.apache.dict.entity.DataCate;
import com.apache.dict.entity.DataItem;
import com.apache.dict.manager.CacheTacticsPlugin;
import com.apache.dict.service.AbstractBaseManager;
import com.apache.dict.vo.ItemListVo;

/**
 * description: 缓存策略接口实现
 *
 * @author Hou DaYu 创建时间：下午12:06:51
 */
public class CacheTacticsPluginImpl extends AbstractBaseManager implements CacheTacticsPlugin {

	private Logger log = Logger.getLogger("CacheTacticsPlugin");

	private static final String ITEM_KEY_PREFIX = "dataItemKey_";//缓存key前缀

	private CacheManager cache;

	public static boolean cacheMark = true;

	@SuppressWarnings("rawtypes")
	public void initItem() {

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					log.info("初始化缓存数据——数据字典 start...");
					long starTime1 = new Date().getTime();
					MethodParam param = new MethodParam("ByProperty", "", " from DataCate", DataCate.class.getName());
					param.setParams("orderList", " order by cate_ename asc");
					param.setResultCache(false);
					List list = dataCateDao.select(param);
					int count = list.size();
					log.info("table [DataCate] query result size[" + count + "] time："
							+ (new Date().getTime() - starTime1) + "ms");

					if (!Validator.isEmpty(list)) {
						long starTime2 = new Date().getTime();
						param = new MethodParam("ByProperty", "", " from DataItem ", DataItem.class.getName());
						param.setParams("orderList", " order by cate_ename asc, item_value asc");
						param.setResultCache(false);
						List mlist = dataItemDao.select(param);
						log.info("table [DataItem] query result size[" + mlist.size() + "] time："
								+ (new Date().getTime() - starTime2) + "ms");
						if (Validator.isEmpty(mlist) || mlist.isEmpty()) {
							return;
						}
						CacheManager cache = getCache();
						for (int i = 0; i < count; i++) {
							DataCate cate = (DataCate) list.get(i);
							log.info("初始化缓存数据——数据字典[" + cate.getCateEname() + "]start");
							if (cache.checkCacheObject(ITEM_KEY_PREFIX + cate.getCateEname())) {
								log.info("初始化缓存数据——数据字典[" + cate.getCateEname() + "]缓存已加载过");
								continue;
							}
							long starTime3 = new Date().getTime();
							List<String> items = new ArrayList<String>();
							Iterator<DataItem> iter = mlist.iterator();
							boolean flag = false;
							while (iter.hasNext()) {
								DataItem item = iter.next();
								String key = "item_" + item.getItemId();
								cache.createCacheObject(key, item);
								if (cate.getCateEname().equals(item.getCateEname())) {
									items.add(key);
									iter.remove();
									flag = true;
								}
								if (flag && !cate.getCateEname().equals(item.getCateEname())) {
									break;
								}
							}
							if (!items.isEmpty()) {
								cache.createCacheObject(ITEM_KEY_PREFIX + cate.getCateEname(), items);
								log.info("初始化缓存数据——数据字典[" + cate.getCateEname() + "][数据项条数" + (items.size()) + "个]["
										+ (new Date().getTime() - starTime3) + "ms]");
							}
						}
					}
				} catch (Exception e) {
					log.error(e);
				}
			}
		}).start();

	}

	@SuppressWarnings("rawtypes")
	public void createItem(String cateEname, String itemId) {
		CacheManager cache = getCache();
		List list = (List) cache.getCacheObjectByKey(ITEM_KEY_PREFIX + cateEname);
		if (Validator.isEmpty(list)) {
			list = new ArrayList();
		}
		list.add("item_" + itemId);
		cache.createCacheObject(ITEM_KEY_PREFIX + cateEname, list);
		cache.removeCacheObject("city_json_" + cateEname);
	}

	@SuppressWarnings("rawtypes")
	public void removeItem(String cateEname, String itemId) {
		CacheManager cache = getCache();
		List list = (List) cache.getCacheObjectByKey(ITEM_KEY_PREFIX + cateEname);
		if (!Validator.isEmpty(list)) {
			list.remove("item_" + itemId);
		}
		cache.createCacheObject(ITEM_KEY_PREFIX + cateEname, list);
		cache.removeCacheObject("city_json_" + cateEname);
	}

	public void removeItems(String cateEname) {
		CacheManager cache = SystemTools.getInstance().getCache("");
		cache.removeCacheObject(ITEM_KEY_PREFIX + cateEname);
		cache.removeCacheObject("city_json_" + cateEname);
	}

	public List<DataItem> getDataItems(ItemListVo vo) {
		CacheManager cache = getCache();
		List<String> list = (List<String>) cache.getCacheObjectByKey(ITEM_KEY_PREFIX + vo.getCateEname());
		List<DataItem> result = new ArrayList<DataItem>();
		if (!Validator.isEmpty(list)) {
			int count = list.size();
			for (int i = 0; i < count; i++) {
				DataItem item = (DataItem) cache.getCacheObjectByKey(list.get(i));
				if (Validator.isEmpty(item))
					continue;
				//				if ("0".equals(item.getItemStatus())) {
				//					continue;
				//				}
				if (Validator.isNotNull(vo.getItemText())) {
					if (Validator.isNull(item.getItemText()) || item.getItemText().indexOf(vo.getItemText()) == -1) {
						continue;
					}
				}
				if (Validator.isNotNull(vo.getItemValue())) {
					if (Validator.isNull(item.getItemValue()) || item.getItemValue().indexOf(vo.getItemValue()) == -1) {
						continue;
					}
				}
				if (Validator.isNotNull(vo.getFatherId())) {
					if (!vo.getFatherId().equals(item.getFatherId())) {
						continue;
					}
				}

				if (Validator.isNotNull(vo.getFatherValue())) {
					if (!vo.getFatherValue().equals(item.getFatherValue())) {
						if (vo.getFatherValue().equals("0") && Validator.isNull(item.getFatherValue())) {
							result.add(item);
							continue;
						}
						continue;
					}
				}
				result.add(item);
			}
		}
		return result;
	}

	private CacheManager getCache() {
		if (null == cache) {
			cache = SystemTools.getInstance().getCache("");
		}
		return cache;
	}

}
